package com.yuanchu.order.searchconfig;

import com.alibaba.fastjson.JSON;
import com.yuanchu.messages.service.MqMessageService;
import com.yuanchu.order.message.OrderMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @version: 1.0
 * @Author: adan
 * @description:
 * @date: 2024-02-23 12:35
 */
@Slf4j
@Configuration
public class PayNotifyConfig implements ApplicationContextAware {

    //交换机
    public static final String PAYNOTIFY_EXCHANGE_TOPIC = "paynotify_exchange_topic";
    //支付结果通知消息类型
    public static final String MESSAGE_TYPE = "payresult_notify";

    //支付结果通知消息类型
    public static final String MESSAGE_KEY = "order_pay_notify";
    public static final String MESSAGE_KEY_GOODS = "order_pay_notify";
    //支付通知优惠券队列
    public static final String PAYNOTIFY_MARKETING_QUEUE = "paynotify_marketing_queue";
    //支付通知用户队列
    public static final String PAYNOTIFY_STORE_QUEUE = "paynotify_store_queue";
    // 支付通知商品队列
    public static final String PAYNOTIFY_GOODS_QUEUE = "paynotify_goods_queue";


    //声明交换机，且持久化
    @Bean(PAYNOTIFY_EXCHANGE_TOPIC)
    public TopicExchange paynotify_exchange_fanout() {
        // 三个参数：交换机名称、是否持久化、当没有queue与其绑定时是否自动删除
        return new TopicExchange(PAYNOTIFY_EXCHANGE_TOPIC, true, false);
    }
    //支付通知优惠券队列,且持久化
    @Bean(PAYNOTIFY_MARKETING_QUEUE)
    public Queue orderDirectMarketingQueue() {
        return QueueBuilder.durable(PAYNOTIFY_MARKETING_QUEUE).build();
    }

    //支付通知用户队列,且持久化
    @Bean(PAYNOTIFY_STORE_QUEUE)
    public Queue orderDirectStoreQueue() {
        return QueueBuilder.durable(PAYNOTIFY_STORE_QUEUE).build();
    }
    @Bean(PAYNOTIFY_GOODS_QUEUE)
    public Queue goodsDirectStoreQueue() {
        return QueueBuilder.durable(PAYNOTIFY_GOODS_QUEUE).build();
    }


    //交换机和支付通知优惠券队列绑定
    @Bean
    public Binding bindingOrderPayqueueMarketing(@Qualifier(PAYNOTIFY_MARKETING_QUEUE) Queue queue, @Qualifier(PAYNOTIFY_EXCHANGE_TOPIC) TopicExchange exchange) {
        // return BindingBuilder.bind(queue).to(exchange);
        return BindingBuilder.bind(queue).to(exchange).with("order.*");
    }

    //交换机和支付通知用户队列绑定
    @Bean
    public Binding bindingOrderPayQueueStore(@Qualifier(PAYNOTIFY_STORE_QUEUE) Queue queue, @Qualifier(PAYNOTIFY_EXCHANGE_TOPIC) TopicExchange exchange) {
        return BindingBuilder.bind(queue).to(exchange).with("order.*");
    }

    //交换机和支付通知商品队列绑定
    @Bean
    public Binding bindingOrderPayQueueGoods(@Qualifier(PAYNOTIFY_GOODS_QUEUE) Queue queue, @Qualifier(PAYNOTIFY_EXCHANGE_TOPIC) TopicExchange exchange) {
        return BindingBuilder.bind(queue).to(exchange).with("order.goods.*");
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        // 获取RabbitTemplate
        RabbitTemplate rabbitTemplate = applicationContext.getBean(RabbitTemplate.class);
        //消息处理service
        MqMessageService mqMessageService = applicationContext.getBean(MqMessageService.class);
        // 设置ReturnCallback
        rabbitTemplate.setReturnCallback((message, replyCode, replyText, exchange, routingKey) -> {
            // 投递失败，记录日志
            log.info("消息发送到队列失败，应答码{}，原因{}，交换机{}，路由键{},消息{}",
                    replyCode, replyText, exchange, routingKey, message);
            // 判断消息是否是int类型
            if (isIntegerByCharacterCheck(message.toString())) {
                // 将消息再添加到消息表
                mqMessageService.addMessage(message.toString(), "orderRefundId", null, null);
            }
            OrderMessage mqMessage = JSON.parseObject(message.toString(), OrderMessage.class);
            //将消息再添加到消息表
            mqMessageService.addMessage(String.valueOf(mqMessage.getOrderId()), String.valueOf(mqMessage.getUserId()),JSON.toJSONString(mqMessage),null);

        });
    }

    public static boolean isIntegerByCharacterCheck(String str) {
        if (str == null || str.isEmpty()) {
            return false;
        }
        for (char c : str.toCharArray()) {
            if (!Character.isDigit(c)) {
                return false;
            }
        }
        return true;
    }
}
